//
//  LcLoadingIndicatorView.m
//  18Birdies
//
//  Created by Lc on 15/4/14.
//  Copyright (c) 2015年 Lc. All rights reserved.
//

#import "LcFont.h"
#import "LcLoadingIndicatorView.h"
#import "LcPreconditions.h"
#import "LcUIUtility.h"
#import "NSDate+Lc.h"
#import "UIColor+Lc.h"
#import "UIView+Lc.h"
#import "ViewControllerManager.h"
#import "BaseViewController.h"
#import "CKLoadingView.h"

@interface LcLoadingIndicatorViewControllerWrapper : BaseViewController

@end

@implementation LcLoadingIndicatorViewControllerWrapper

- (UIStatusBarStyle)preferredStatusBarStyle {
  UIViewController* currentViewController =
      [[ViewControllerManager sharedInstance] currentViewController];
  if (currentViewController != nil) {
    return currentViewController.preferredStatusBarStyle;
  }
  return UIStatusBarStyleLightContent;
}

@end

@interface LcLoadingIndicatorView ()
@property(nonatomic, weak) CKLoadingView* progressView;
@property(nonatomic, assign)
    long long modalLoadingIndicatorViewStartShowingTime;
@end

@implementation LcLoadingIndicatorView

+ (LcLoadingIndicatorView*)loadingIndicatorViewWithSytle:
    (LcLoadingIndicatorViewStyle)style {
  if (style == LcLoadingIndicatorViewStyleNormal) {
    return [self createNormalLoadingIndicatorView];
  } else if (style == LcLoadingIndicatorViewStyleModal) {
    return [self createModalLoadingIndicatorView];
  } else {
    LC_FAIL();
    return nil;
  }
}

+ (LcLoadingIndicatorView*)createNormalLoadingIndicatorView {
  CKLoadingView* progressView = [CKLoadingView loadFromBundle];
  LcLoadingIndicatorView* loadingIndicatorView =
      [[self alloc] initWithFrame:progressView.bounds];
  loadingIndicatorView.userInteractionEnabled = NO;
  loadingIndicatorView.hidden = YES;
  [loadingIndicatorView addSubview:progressView];
  NSLayoutConstraint* centerX =
  [NSLayoutConstraint constraintWithItem:progressView
                               attribute:NSLayoutAttributeCenterX
                               relatedBy:NSLayoutRelationEqual
                                  toItem:loadingIndicatorView
                               attribute:NSLayoutAttributeCenterX
                              multiplier:1
                                constant:0];
  NSLayoutConstraint* centerY =
  [NSLayoutConstraint constraintWithItem:progressView
                               attribute:NSLayoutAttributeCenterY
                               relatedBy:NSLayoutRelationEqual
                                  toItem:loadingIndicatorView
                               attribute:NSLayoutAttributeCenterY
                              multiplier:1
                                constant:0];
  progressView.translatesAutoresizingMaskIntoConstraints = NO;
  [NSLayoutConstraint activateConstraints:@[ centerX, centerY ]];
  loadingIndicatorView.progressView = progressView;
  loadingIndicatorView->_style = LcLoadingIndicatorViewStyleNormal;
  return loadingIndicatorView;
}

+ (LcLoadingIndicatorView*)createModalLoadingIndicatorView {
  LcLoadingIndicatorView* loadingIndicatorView =
      [[self alloc] initWithFrame:CGRectMake(0, 0, [LcUIUtility screenWidth],
                                             [LcUIUtility screenHeight])];
  loadingIndicatorView.backgroundColor =
      [LC_COLOR_DARK colorWithAlphaComponent:0.3];
  loadingIndicatorView.userInteractionEnabled = YES;
  loadingIndicatorView.alpha = 0;
  loadingIndicatorView.hidden = YES;

  CKLoadingView* progressView = [CKLoadingView loadFromBundle];
  const int BACKGROUND_VIEW_SIZE = 80;
  UIView* backgroundView =
      [[UIView alloc] initWithFrame:CGRectMake(0, 0, BACKGROUND_VIEW_SIZE,
                                               BACKGROUND_VIEW_SIZE)];
  backgroundView.center = CGPointMake([LcUIUtility screenCenterX],
                                      [LcUIUtility screenHeight] * 2 / 5);
  backgroundView.backgroundColor = [UIColor clearColor];
  backgroundView.layer.cornerRadius = 12;
  backgroundView.layer.masksToBounds = YES;
  progressView.center =
      CGPointMake(BACKGROUND_VIEW_SIZE / 2, BACKGROUND_VIEW_SIZE / 2);
  [backgroundView addSubview:progressView];

  [loadingIndicatorView addSubview:backgroundView];
  loadingIndicatorView.progressView = progressView;
  loadingIndicatorView->_style = LcLoadingIndicatorViewStyleModal;
  return loadingIndicatorView;
}

- (void)show {
  LC_CHECK_IS_MAIN_THREAD();
  [self.progressView startAnimating];
  self.hidden = NO;
  if (self.style == LcLoadingIndicatorViewStyleNormal) {
  } else {
    self.modalLoadingIndicatorViewStartShowingTime = [NSDate currentTimeMillis];
    [UIView animateWithDuration:0.3
                     animations:^{
                       self.alpha = 1.0;
                     }];
  }
}

- (void)hide {
  LC_CHECK_IS_MAIN_THREAD();
  if (self.style == LcLoadingIndicatorViewStyleNormal) {
    [self.progressView stopAnimating];
    self.hidden = YES;
  } else {
    const long long MIN_SHOWING_TIME = 350;
    long long elapsed = [NSDate currentTimeMillis] -
                        self.modalLoadingIndicatorViewStartShowingTime;
    if (elapsed < MIN_SHOWING_TIME && elapsed >= 0) {
      NSTimeInterval delay = (MIN_SHOWING_TIME - elapsed) / 1000.0;
      dispatch_after(
          dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC)),
          dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.3
                animations:^{
                  self.alpha = 0;
                }
                completion:^(BOOL finished) {
                  [self.progressView stopAnimating];
                  self.hidden = YES;
                  self.window.hidden = YES;
                }];
          });
    } else {
      [UIView animateWithDuration:0.3
          animations:^{
            self.alpha = 0;
          }
          completion:^(BOOL finished) {
            [self.progressView stopAnimating];
            self.hidden = YES;
            self.window.hidden = YES;
          }];
    }
  }
}

static LcLoadingIndicatorView* normalLoadingIndicatorView;
static LcLoadingIndicatorView* modalLoadingIndicatorView;
static UIWindow* window;
static UIWindow* modalWindow;

+ (void)showNormal:(BOOL)white {
  LC_CHECK_IS_MAIN_THREAD();
  if (window == nil) {
    window = [UIApplication sharedApplication].windows[0];
  }
  if (normalLoadingIndicatorView == nil) {
    normalLoadingIndicatorView = [LcLoadingIndicatorView
        loadingIndicatorViewWithSytle:LcLoadingIndicatorViewStyleNormal];
    [window addSubview:normalLoadingIndicatorView];
    NSLayoutConstraint* centerX =
        [NSLayoutConstraint constraintWithItem:normalLoadingIndicatorView
                                     attribute:NSLayoutAttributeCenterX
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:window
                                     attribute:NSLayoutAttributeCenterX
                                    multiplier:1
                                      constant:0];
    NSLayoutConstraint* centerY =
        [NSLayoutConstraint constraintWithItem:normalLoadingIndicatorView
                                     attribute:NSLayoutAttributeCenterY
                                     relatedBy:NSLayoutRelationEqual
                                        toItem:window
                                     attribute:NSLayoutAttributeCenterY
                                    multiplier:1
                                      constant:0];
    normalLoadingIndicatorView.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:@[ centerX, centerY ]];
  }
  [window bringSubviewToFront:normalLoadingIndicatorView];
  normalLoadingIndicatorView.white = white;
  [normalLoadingIndicatorView show];
}

+ (void)hideNormal {
  LC_CHECK_IS_MAIN_THREAD();
  if (normalLoadingIndicatorView != nil) {
    [normalLoadingIndicatorView hide];
  }
}

+ (void)showModal {
  LC_CHECK_IS_MAIN_THREAD();
  if (modalWindow == nil) {
    [self createModalWindow];
  }
  if (modalLoadingIndicatorView == nil) {
    modalLoadingIndicatorView = [LcLoadingIndicatorView
        loadingIndicatorViewWithSytle:LcLoadingIndicatorViewStyleModal];
    [modalWindow addSubview:modalLoadingIndicatorView];
  }
  modalWindow.hidden = NO;
  [modalLoadingIndicatorView show];
}

+ (void)hideModal {
  LC_CHECK_IS_MAIN_THREAD();
  if (modalLoadingIndicatorView != nil) {
    [modalLoadingIndicatorView hide];
  }
}

+ (BOOL)isShow {
  if (modalLoadingIndicatorView != nil) {
    return YES;
  }
  return NO;
}

+ (void)createModalWindow {
  modalWindow = [[UIWindow alloc]
      initWithFrame:CGRectMake(0, 0, [LcUIUtility screenWidth],
                               [LcUIUtility screenHeight])];
  modalWindow.windowLevel = UIWindowLevelAlert;
  modalWindow.rootViewController = [[LcLoadingIndicatorViewControllerWrapper alloc] init];
}

@end
